#!/usr/bin/env python

import numpy as np
import os, serial,time,socket,sys,json,logging,requests,getopt
from meas_data import meas_data
# import the server implementation
sensor="tristar"
pathname = os.path.dirname(sys.argv[0])        
abspath=os.path.abspath(pathname)

idfile=abspath+"/id.json"
id_conf=0
try:
	idf=open(idfile,"r")
	id_conf=json.load(idf)['id']
	idf.close()
except:
	id_conf=0

configfile=abspath+"/config.json"
try:
	cf=open(configfile,"r")
except:
	cf=open(configfile+".template","r")

log_conf=json.load(cf)
cf.close()

channel_names=[]
channel_info={}

parameter={"device":socket.gethostname(),"deviceid":"FF","mean_count":5,"ring_length":10,"wait":0.5,"cycle":10,"check_last":5,"check_last_shrinking":0.9,"gpg_keyid":"","digits":3,"store_dir":"/home/pi/log/","multiplicator":1000,"sensor":sensor,"sigma":3}
for n in parameter:
  if n in log_conf:
    parameter[n]=log_conf[n]

# configure tristar
btristar=False
if sensor in log_conf:
  btristar=True
  if "enable" in log_conf[sensor]:
    if log_conf[sensor]['enable'] == 0:
      btristar=False
  bmqtt=False
  if "mqtt" in log_conf:
    bmqtt=True
    lcmq=log_conf['mqtt']
    mbroker=""
    if 'broker' in lcmq:
      mbroker=lcmq['broker']
    else:
      bmqtt=False
    mport=1883
    if 'port' in lcmq:
      mport=lcmq['port']  
  if "sqlserver" in log_conf:
    hostname="localhost"
    port=8080
  if btristar:
    import smbus
    from pymodbus.client.sync import ModbusSerialClient as ModbusClient
    for n in parameter:
      if n in log_conf[sensor]:
        parameter[n]=log_conf[sensor][n]
    tri_port='/dev/ttyUSB0'
    if "port" in log_conf[sensor]:
      tri_port=log_conf[sensor]['port']
    tri_baud=9600
    if "baud" in log_conf[sensor]:
      tri_baud=log_conf[sensor]['baud']
    tri_timeout=1
    if "timeout" in log_conf[sensor]:
      tri_timeout=log_conf[sensor]['timeout']
    try:
      triclient = ModbusClient(method='rtu', port=tri_port, baudrate=tri_baud, timeout=tri_timeout)
    except:
      btristar=False
    else:
      triclient.connect()
      check_last=0
      if "check_last" in log_conf[sensor]:
        check_last=log_conf[sensor]['check_last']
      tsl_sigma=parameter['sigma']
      parameter["i2c"]=0
      if "sigma" in log_conf[sensor]:
        parameter['sigma']=int(log_conf['vedirect']['sigma'])
        if parameter['sigma'] < 1:
          parameter['sigma']=1
      varnamess={"volt_scale":"volt_scale","amp_scale":"amp_scale","volt_bat":"voltage","volt_bat_sens":"voltage","volt_arr":"voltage","amp_bat":"current","amp_arr":"current","temp_heatsink":"temperature","temp_bat":"temperature","ah_res":"charge","ah_tot":"charge","kwh_res":"kwh","kwh_tot":"kwh","watt_in":"power","watt_out":"power","hour_tot":"hour","state":"state","volt_sweep_mp":"voltage","volt_sweep_oc":"voltage"}
      mult={"volt_scale":1000000,"amp_scale":1000000,"volt_bat":1000,"volt_bat_sens":1000,"volt_arr":1000,"amp_bat":1000,"amp_arr":1000,"temp_heatsink":1,"temp_bat":1,"ah_res":1,"ah_tot":1,"kwh_res":1,"kwh_tot":1,"watt_in":1000,"watt_out":1000,"hour_tot":1,"state":1,"volt_sweep_mp":1000,"volt_sweep_oc":1000}
      sensort={"volt_scale":"tristar","amp_scale":"tristar","volt_bat":"tristar_battery","volt_bat_sens":"tristar_sense","volt_arr":"tristar_array","amp_bat":"tristar_battery","amp_arr":"tristar_array","temp_heatsink":"tristar","temp_bat":"tristar_battery","ah_res":"tristar_battery","ah_tot":"tristar","kwh_res":"tristar_battery","kwh_tot":"tristar","watt_in":"tristar_array","watt_out":"tristar_battery","hour_tot":"tristar","state":"tristar","volt_sweep_mp":"tristar_array","volt_sweep_oc":"tristar_array"}
      i2c={"volt_scale":0,"amp_scale":0,"volt_bat":0,"volt_bat_sens":0,"volt_arr":0,"amp_bat":0,"amp_arr":0,"temp_heatsink":0,"temp_bat":0,"ah_res":0,"ah_tot":0,"kwh_res":0,"kwh_tot":0,"watt_in":0,"watt_out":0,"hour_tot":0,"state":0,"volt_sweep_mp":1,"volt_sweep_oc":2}
      for i in ["volt_scale","amp_scale","volt_bat","volt_bat_sens","volt_arr","amp_bat","amp_arr","temp_heatsink","temp_bat","ah_res","ah_tot","kwh_res","kwh_tot","watt_in","watt_out","hour_tot","state","volt_sweep_mp","volt_sweep_oc"]:
        parch=parameter
        parch["var_name"]=i
        parch["multiplicator"]=mult[i]
        channel_info[i]={"meas_data": meas_data(parch)}
        if bmqtt and ("mqtt" in log_conf[sensor]):
          channel_info[i]['meas_data'].set_mqtt(broker=mbroker,port=mport)
        if "sqlserver" in log_conf:
          channel_info[i]['meas_data'].set_sql(host=hostname,port=port)

div_scale=2**31
if btristar:
  while True:
  
    try:
      rr = triclient.read_holding_registers(0,90,unit=1)
    except:
      print("could not get data from tristar")
    else:
      try:
        volt_scale=float(rr.registers[0]*65536+rr.registers[1])/div_scale
      except:
        print("could not read from tristar")
      else:
        amp_scale=float(rr.registers[2]*65536+rr.registers[3])/div_scale
        channel_info["volt_scale"]['meas_data'].append(volt_scale)
        channel_info["amp_scale"]['meas_data'].append(amp_scale)
        channel_info["volt_bat"]['meas_data'].append(float(rr.registers[25])*volt_scale)
        channel_info["volt_bat_sens"]['meas_data'].append(float(rr.registers[26])*volt_scale)
        channel_info["volt_arr"]['meas_data'].append(float(rr.registers[27])*volt_scale) # Array voltage
        channel_info["amp_bat"]['meas_data'].append(float(rr.registers[28])*amp_scale) # Battery current
        channel_info["amp_arr"]['meas_data'].append(float(rr.registers[29])*amp_scale) # Array current
        channel_info["temp_heatsink"]['meas_data'].append(int(rr.registers[35])) # Temperature heatsink
        channel_info["temp_bat"]['meas_data'].append(int(rr.registers[36])) # Temperature battery
        channel_info["ah_res"]['meas_data'].append(int(rr.registers[52] * 65536 + rr.registers[53])) # Ah resetable
        channel_info["ah_tot"]['meas_data'].append(int(rr.registers[54] * 65536 + rr.registers[55])) # Ah total
        channel_info["kwh_res"]['meas_data'].append(int(rr.registers[56])) # kwh resetable
        channel_info["kwh_tot"]['meas_data'].append(int(rr.registers[57])) # kwh total
        channel_info["watt_in"]['meas_data'].append(float(rr.registers[58])*volt_scale*amp_scale*2**13) # Power in
        channel_info["watt_out"]['meas_data'].append(float(rr.registers[59])*volt_scale*amp_scale*2**13) # Power out
        channel_info["hour_tot"]['meas_data'].append(int(rr.registers[42] * 65536 + rr.registers[43])) # hour total
        channel_info["state"]['meas_data'].append(int(rr.registers[50])) # State
        channel_info["volt_sweep_mp"]['meas_data'].append(float(rr.registers[61])*volt_scale) # Array voltage
        channel_info["volt_sweep_oc"]['meas_data'].append(float(rr.registers[62])*volt_scale) # Array voltage
  

    time.sleep(parameter['wait'])


# close the client
print("done")


